from git import Repo
from pathlib import Path
from datetime import datetime

gitee_link = "https://gitee.com/"
repo_name = "APIJSON"
repo_link = gitee_link + "tencent/" + repo_name
commits_link = gitee_link + "tencent/" + repo_name + "/commits/master"
authors_link = gitee_link + "tencent/" + repo_name + "/contributors"
branches_link = gitee_link + "tencent/" + repo_name + "/branches"
branch_link = gitee_link + "tencent/" + repo_name + "/tree/"

md = f"# {repo_name} Project Data Analysis\n\n"

if Path(repo_name).exists():
    repo = Repo(repo_name)
else:
    print("Cloning Repo...")
    repo = Repo.clone_from(repo_link, repo_name)
    print("Finished Cloning!")

# Overview
repo_commits = list(repo.iter_commits())
first_commit = repo_commits[-1]
latest_commit = repo_commits[0]
start_date = datetime.fromtimestamp(first_commit.authored_date)
latest_date = datetime.fromtimestamp(latest_commit.authored_date)
md += f"## Start Date: {start_date}\n"
md += f"## Latest Update: {latest_date}\n"
md += f"## Commits: {len(repo_commits)} [{commits_link}]\n\n"

# Branches
gitee = repo.remotes[0]
gitee_branches = [ref.name[7:] for ref in gitee.refs if ref.name != "origin/HEAD"]
gitee_branches.remove("master")
repo_branches = ["master"] + gitee_branches
md += f"## Branches: {len(repo_branches)} [{branches_link}]\n\n"

# Authors
author_data = {}
for commit in repo_commits:
    author = commit.author.name
    if author not in author_data:
        author_data[author] = 1
    else:
        author_data[author] += 1
author_data = sorted(author_data.items(), key=lambda data: data[1], reverse=True)
md += f"## Authors: {len(author_data)} [{authors_link}]\n\n"

md += "## Branches\n"
for branch in repo_branches:
    md += f"### {branch}: [{branch_link}{branch}]\n\n"

md += "## Top 10 Authors\n"
for i in range(10):
    author = author_data[i]
    name = author[0].replace(" ", "-")
    commits = author[1]
    md += f"{i + 1}. {name}: [{gitee_link + name}]: {commits} commits\n"

Path("report.md").write_text(md, "UTF-8")